<style lang="scss"></style>

<script>
export default {
  props: {
    value: {
      type: Boolean,
      required: true,
      default() {
        return false
      }
    },
    showPreviewQRBtn: {
      type: Boolean,
      default: true
    },
    colSize: {
      type: Number,
      default: 24
    },
    data: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      points: [],
      createPointDialog: {
        visible: false,
        form: {
          name: ''
        },
        formRules: {
          name: [
            { type: 'string', required: true, message: '请输入点位名称', trigger: ['change', 'blur'] }
          ]
        }
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isShow() {
      return this.value
    }
  },
  watch: {
    isShow(isShow) {
      if (!isShow) { return }

      this.points = this.data
      /**
             * 传入数据的结构必须为
             * [
             *      {
             *          name:'点位名称',
             *          QRCode:二维码数据
             *      }
             * ]
             */
    }
  },
  methods: {
    savePoints() {
      this.$emit('confirm', this.points)
    },
    moveUp(index) {
      if (index <= 0) return

      const point = this.points.at(index)
      const prevPoint = this.points.at(index - 1)

      this.$set(this.points, index, prevPoint)
      this.$set(this.points, index - 1, point)
    },
    moveDown(index) {
      const lastIndex = this.points.length - 1
      if (index >= lastIndex) return

      const point = this.points.at(index)
      const nextPoint = this.points.at(index + 1)

      this.$set(this.points, index, nextPoint)
      this.$set(this.points, index + 1, point)
    },
    isFirstItem(index) {
      return index <= 0
    },
    isLastItem(index) {
      const len = this.points.length
      return index >= (len - 1)
    },
    closeDialog() {
      this.dialogVisible = false
    },
    closeCreatePointDialog() {
      this.createPointDialog.visible = false
    },
    resetCreatePointDialogForm() {
            this.$refs?.pointForm.resetFields()
    },
    createPoint() {
            this.$refs?.pointForm.validate(flag => {
              if (!flag) return

              this.points.push({
                name: this.createPointDialog.form.name,
                QRCode: null
              })

              this.closeCreatePointDialog()
              this.resetCreatePointDialogForm()
            })
    },
    openQRCode(point) {
      const img = new Image()
      img.src = point.QRCode

      const newTabPage = window.open('', '_blank')
      const htmlContent = `
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                    <h3 style="padding: 50px 0;">点位：${point.name} 二维码</h3>
                    ${img.outerHTML}
                </div>
            `
      newTabPage.document.write(htmlContent)
      newTabPage.document.title = `点位二维码 - ${point.name}`
    },
    removePoint(index) {
      console.log(index)
      this.points.splice(index, 1)
    },
    isQRDownloadDisabled(point) {
      return !point.QRCode
    },
    isPreviewQRDisabled(point) {
      return !point.QRCode
    },
    isQRActionDisabeld(point) {
      return !point.QRCode
    },
    showCreatePointDialog() {
      this.createPointDialog.visible = true
    },
    b64toBlob(b64Data, contentType, sliceSize) {
      contentType = contentType || ''
      sliceSize = sliceSize || 512

      const byteCharacters = atob(b64Data)
      const byteArrays = []

      for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize)

        const byteNumbers = new Array(slice.length)
        for (let i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i)
        }

        const byteArray = new Uint8Array(byteNumbers)
        byteArrays.push(byteArray)
      }

      return new Blob(byteArrays, { type: contentType })
    },
    downloadBase64Img(base64Data, name) {
      const blobData = this.b64toBlob(base64Data.substring(base64Data.indexOf(',') + 1), 'application/octet-stream')
      const blobUrl = URL.createObjectURL(blobData)

      const link = document.createElement('a')

      link.href = blobUrl
      link.download = name

      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    downloadQRCode(point) {
      this.downloadBase64Img(point.QRCode, `点位二维码_${point.name}.jpg`)
    }
  }
}
</script>

<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="点位编辑"
    width="40%"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
  >
    <div v-loading="false" class="body">
      <el-table :data="points" style="width: 100%">
        <el-table-column prop="name" label="点位名称" width="280">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.name"
              :disabled="disabled"
            />
          </template>
        </el-table-column>

        <el-table-column prop="name" label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="!disabled"
              plain
              size="mini"
              icon="el-icon-top"
              :disabled="isFirstItem(scope.$index)"
              @click="moveUp(scope.$index)"
            />
            <el-button
              v-if="!disabled"
              plain
              size="mini"
              icon="el-icon-bottom"
              :disabled="isLastItem(scope.$index)"
              @click="moveDown(scope.$index)"
            />

            <el-button
              plain
              size="mini"
              :disabled="isPreviewQRDisabled(scope.row)"
              @click="openQRCode(scope.row)"
            >
              查看二维码
            </el-button>

            <el-button
              plain
              size="mini"
              type="primary"
              :disabled="isQRDownloadDisabled(scope.row)"
              @click="downloadQRCode(scope.row)"
            >
              下载二维码
            </el-button>

            <el-button
              v-if="!disabled"
              plain
              type="danger"
              size="mini"
              @click="removePoint(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer">
      <el-button v-if="!disabled" type="primary" @click="showCreatePointDialog">
        添加点位
      </el-button>

      <el-button v-if="!disabled" type="primary" @click="savePoints">
        保存
      </el-button>

      <el-button @click="closeDialog">
        取消
      </el-button>
    </div>

    <el-dialog
      :visible.sync="createPointDialog.visible"
      title="点位编辑"
      :close-on-click-modal="false"
      width="35%"
      destroy-on-close
      append-to-body
    >
      <div v-loading="false" class="body">
        <el-form
          ref="pointForm"
          :model="createPointDialog.form"
          :rules="createPointDialog.formRules"
          label-width="80px"
        >
          <el-form-item
            label="点位名称"
            prop="name"
          >
            <el-input
              v-model="createPointDialog.form.name"
            />
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer">

        <el-button type="primary" @click="createPoint">
          保存
        </el-button>

        <el-button @click="closeCreatePointDialog">
          取消
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
